<script setup lang="ts">
import useCategoraryStore from '@/store/modules/category'
import { reqAttr, reqAddUpdateAttr, reqDelAttr } from '@/api/product/attr/index'
import { watch, ref, reactive, nextTick,onBeforeUnmount } from 'vue'
import type { AttrResponseData, Attr, DelResponse } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus';
const categoraryStore = useCategoraryStore()
// 定义卡片内部切换
const scene = ref<number>(0)  //0 table 1 添加
const attrArr = ref<Attr[]>([])
// 准备一个数组，用于存储对应的组件实例el-input
const inputArr = ref<any>([])
// 收集新增数据
const attrParams = reactive<Attr>({
  attrName: "",
  attrValueList: [], //新增的属性值数组
  categoryId: '',
  categoryLevel: 3, //代表三级分类
})
// 监听c3Id的变化
watch(
  () => categoraryStore.c3Id,
  () => {
    // 每次变化需要清空数据
    attrArr.value = []
    // 保证三级分类有id
    if (!categoraryStore.c3Id) return
    getAttr()
  },
)

// 获取数据
const getAttr = async () => {
  try {
    const { c1Id, c2Id, c3Id } = categoraryStore
    const res: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
    if (res.code === 200) {
      attrArr.value = res.data
    }
  } catch (error) {
    console.log(error)
  }
}

// 添加属性按钮的回调
const addAttr = () => {
  // 清空之前数据 合并对象，不用一个一个清除
  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [], //新增的属性值数组
    categoryId: attrParams.categoryId = categoraryStore.c3Id,
    categoryLevel: 3, //代表三级分类
  })
  // 每次打开前先清空id
  attrParams.id = undefined
  scene.value = 1
}

const save = async () => {
  // @ts-ignore
  const res = await reqAddUpdateAttr(attrParams)
  if (res.code == 200) {
    // 切换场景
    scene.value = 0
    // 弹出提示
    ElMessage.success(attrParams.id ? "修改成功" : "添加成功")
    // 刷新列表
    getAttr()
  }
}

// 修改已有属性按钮的回调
const updateAttr = (row: any) => {
  scene.value = 1
  //进行深拷贝 将已有属性赋值给attrParams
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

const cancel = () => {
  scene.value = 0
}

const addAttrValue = () => {
  // 点击添加时向数组添加一个对象
  attrParams.attrValueList.push({
    valueName: '',
    flag: true //控制每一个属性值的显示
  })
  nextTick(() => {
    // @ts-ignore
    inputArr.value[inputArr.value.length - 1].focus()
  })
}
const del = (index: any) => {
  console.log(index);
  // 删除
  attrParams.attrValueList.splice(index, 1)
}
const toLook = (row: any, $index: number) => {
  // 非法情况判断
  if (row.valueName.trim() == "") {
    attrParams.attrValueList.splice($index, 1) //删除对应属性值元素为空的值
    ElMessage.error("请输入内容")
    return;
  }
  // 非法情况2：属性值相同不可以重复
  const repeat = attrParams.attrValueList.find((item) => {
    if (item != row) { //必须要把当前项摘出去，否则必会重复
      return item.valueName === row.valueName
    }
  })
  if (repeat) {
    attrParams.attrValueList.splice($index, 1) //删除对应属性值元素为空的值
    ElMessage.error("属性值重复")
    return;
  }
  row.flag = false
}

const toChange = (row: any, $index: number) => {
  row.flag = true
  console.log(inputArr.value[$index]);
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}

const deleteAttr = async (id: number) => {
  try {
    const res: DelResponse = await reqDelAttr(id)
    if (res.code == 200) {
      ElMessage.success("删除成功")
      getAttr()
    }
  } catch (error) {
    console.log(error)
  }
}

//路由组件销毁后，相关数据要清空
onBeforeUnmount(()=>{
  categoraryStore.$reset()
})
</script>
<template>
  <div class="attr">
    <!-- 三级分类 -->
    <Categrary :scene="scene" />

    <!-- 两个卡片 要么teble 要么添加 v-if -->
    <el-card style="margin: 20px 0">
      <!-- 内容 -->
      <div v-show="!scene">
        <el-button type="primary" icon="plus" style="margin-bottom: 20px" :disabled="!categoraryStore.c3Id"
          @click="addAttr">
          添加属性
        </el-button>
        <el-table border :data="attrArr">
          <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
          <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row }">
              <el-tag style="margin: 10px" v-for="item in row.attrValueList" :key="item.id" :disable-transitions="false">
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <!-- @vue-ignore -->
            <template #="{ row, $index }">
              <!-- 修改已有属性按钮的回调 -->
              <el-button type="warning" icon="Edit" circle @click="updateAttr(row)" />
              <!-- {{ scope.row }} -->
              <!-- 添加确认框 -->
              <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" icon="InfoFilled"
                icon-color="red" title="确定要删除该词条吗" @confirm="deleteAttr(row.id)">
                <template #reference>
                  <el-button type="danger" icon="Delete" circle />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input placeholder="请输入属性的名称" v-model="attrParams.attrName">
            </el-input>
          </el-form-item>
        </el-form>
        <!-- 根据是否有值判断是否禁用 -->
        <el-button type="primary" :disabled="!attrParams.attrName" @click="addAttrValue">添加属性值</el-button>
        <el-button type="text" @click="cancel">取消</el-button>
        <el-table border style="margin: 10px 0;" :data="attrParams.attrValueList">
          <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <!-- row是input对象 -->
              <!-- 编辑模式 -->
              <el-input placeholder="请输入属性值名称" v-model="row.valueName" v-show="row.flag"
                :ref="(vc: any) => inputArr[$index] = vc" @blur="toLook(row, $index)"></el-input>
              <!-- 查看模式 -->
              <div v-show="!row.flag" @click="toChange(row, $index)" style="min-width:200px;">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <!-- @vue-ignore -->
            <template #="{ row, $index }">
              <!-- {{ scope.row }} -->
              <!-- 添加确认框 -->
              <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" icon="InfoFilled"
                icon-color="red" title="确定要删除该词条吗" @confirm="del($index)">
                <template #reference>
                  <el-button type="warning" icon="Delete" circle />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save" :disabled="!attrParams.attrValueList.length">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>

    </el-card>
  </div>
</template>
<style scoped></style>
